# coding=utf-8

import xbmcplugin
import xbmcgui
import xbmc
import sys
import subprocess
import urlparse
import xbmcaddon

from resources.lib.Importer import Importer
from resources.lib.Recorder import Recorder

PLUGIN = "plugin.audio.recorder"

def getParams():
	paramString = urlparse.urlparse(sys.argv[2])
	return urlparse.parse_qs(paramString.query)

def convertToUnicode(dictionary):
	for key in dictionary.keys():
		dictionary[key][0] = dictionary[key][0].decode("utf-8")
		key = key.decode("utf-8")
	return dictionary

def createListing():
	return imp.getStreams()

def sendToXbmc(listing):
	rec.send(listing)

def showMessage(header, msg, icon):
	xbmc.executebuiltin(("XBMC.Notification(%s, %s, 5000, %s)" % (header, msg, icon)).encode("utf-8"))

thisPlugin = int(sys.argv[1])
addon = xbmcaddon.Addon(id=PLUGIN)
_path = addon.getAddonInfo("path")

imp = Importer(_path + "/resources/streams.xml")
rec = Recorder(thisPlugin, PLUGIN)

params = convertToUnicode(getParams())

if "mode" in params:
	if params["mode"][0] == "record":
		rec.record(params["url"][0])
	elif params["mode"][0] == "edit":
		newURL = rec.editURL(params["url"][0], params["station"][0])
		if newURL != params["url"][0]:
			imp.editStreamURL(params["station"][0], newURL)
			xbmc.executebuiltin("Container.Refresh")
	elif params["mode"][0] == "add":
		newStation = rec.addStation()
		if newStation != "":
			if imp.hasStation(newStation):
				showMessage(u"Error", u"Station " + u'"' + newStation + u'" already exists!', "DefaultIconError.png")
			else:
				newURL = rec.editURL("", newStation)
				if newURL != "":
					imp.addStation(newStation, newURL)
					xbmc.executebuiltin("Container.Refresh")
	elif params["mode"][0] == "remove":
		imp.removeStation(params["station"][0])
		xbmc.executebuiltin("Container.Refresh")
else:
	listing = createListing()
	sendToXbmc(listing)
	xbmcplugin.endOfDirectory(thisPlugin)
